package com.dhh.sky.activity;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import org.json.JSONObject;
import com.dhh.sky.R;
import com.dhh.sky.SDAApplication;
import com.dhh.sky.util.JsonKeys;
import com.microsoft.live.LiveConnectClient;
import com.microsoft.live.LiveDownloadOperation;
import com.microsoft.live.LiveOperation;
import com.microsoft.live.LiveOperationException;
import com.microsoft.live.LiveUploadOperationListener;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Environment;
import android.widget.RemoteViews;

public class DownloadService extends IntentService {
	public static final String OP_DOWNLOAD = "DOWNLOAD";
	public static final String OP_UPLOAD = "UPLOAD";
	private LiveConnectClient mClient;
	
	public DownloadService() {
		super("DownloadService");
	}
	
	@Override
	protected void onHandleIntent(Intent intent){
		String operation = intent.getExtras().getString("operation");
		if(OP_DOWNLOAD.equals(operation)){
			String source = intent.getExtras().getString("source");
			String name = intent.getExtras().getString("name");
			doDownload(source,name);
		}else if(OP_UPLOAD.equals(operation)){
			String filePath = intent.getExtras().getString("filePath");
			String mCurrentFolderId = intent.getExtras().getString("mCurrentFolderId");
			String name = intent.getExtras().getString("name");
			doUpload(filePath,mCurrentFolderId,name);
		}		
	}
	
	private void doDownload(String source,final String name){
		final Notification notification = new Notification(R.drawable.ic_launcher, this.getString(R.string.msg_start_download)+name, System.currentTimeMillis());
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.download_progress);
        notification.contentView.setImageViewResource(R.id.status_icon, R.drawable.ic_download_s);
        notification.contentView.setTextViewText(R.id.status_text, this.getString(R.string.msg_start_download)+" "+name);
        notification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);        
        
        Intent it = new Intent(this,FileViewActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, it, 0);
        notification.contentIntent = pendingIntent;
		final NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(41, notification); 
        
        mClient = ((SDAApplication) getApplication()).getConnectClient();
        try {
        	LiveDownloadOperation operation = mClient.download(source);
        	File dir = new File(Environment.getExternalStorageDirectory().getPath()+"/SkyDrive");
			if(!dir.exists()) dir.mkdir();										
			File file = new File(Environment.getExternalStorageDirectory().getPath()+"/SkyDrive/"+name);
			if(file.exists()){
				file.delete();
				file.createNewFile();
			}
			InputStream input = new BufferedInputStream(operation.getStream());							
			int aSize = operation.getContentLength();
            OutputStream output = new BufferedOutputStream(new FileOutputStream(file));

            byte data[] = new byte[operation.getContentLength()/10];
            long total = 0;
            int count;
            int current = 10;
            while ((count = input.read(data)) != -1) {
                total += count;							               
                output.write(data, 0, count);    				                
                
                int percentCompleted = computePrecentCompleted(aSize, aSize-total);
				if(percentCompleted>=current || percentCompleted==100){
					notification.contentView.setProgressBar(R.id.status_progress, 100, current, false);
					current +=10;
					notificationManager.notify(41, notification);
				}
                
            }

            output.flush();
            output.close();
            input.close();
            
            notification.contentView.setProgressBar(R.id.status_progress, 100, 100, false);
            notification.contentView.setTextViewText(R.id.status_text, name);
            notification.contentView.setImageViewResource(R.id.status_icon, R.drawable.ic_yes);			
            notificationManager.notify(41, notification);
            
		} catch (Exception e1) {
			notification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
            notification.contentView.setTextViewText(R.id.status_text, this.getString(R.string.msg_download_fail)+" "+name+".");
            notification.contentView.setImageViewResource(R.id.status_icon, R.drawable.ic_delete);				            
            notificationManager.notify(41, notification);
		}		
	}
	
	private void doUpload(final String filePath,final String mCurrentFolderId,final String name){
		final Notification notification = new Notification(R.drawable.ic_launcher, this.getString(R.string.msg_start_upload)+" "+name, System.currentTimeMillis());
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.contentView = new RemoteViews(getApplicationContext().getPackageName(), R.layout.download_progress);
        notification.contentView.setImageViewResource(R.id.status_icon, R.drawable.ic_up_s);
        notification.contentView.setTextViewText(R.id.status_text, this.getString(R.string.msg_uploading)+" "+name);
        notification.contentView.setProgressBar(R.id.status_progress, 100, 0, false);
        Intent it = new Intent(this,FileListActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, it, 0);
        notification.contentIntent = pendingIntent;
		final NotificationManager notificationManager = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(42, notification);      
        
        File file = new File(filePath);    
		mClient = ((SDAApplication) getApplication()).getConnectClient();
        mClient.uploadAsync(mCurrentFolderId,
				file.getName(), 
				file, 
				new LiveUploadOperationListener() {
					int current = 0;
					@Override
					public void onUploadProgress(int totalBytes,int bytesRemaining, LiveOperation operation) {						
						int percentCompleted = computePrecentCompleted(totalBytes, bytesRemaining);
						if(percentCompleted>=current+5 || percentCompleted==100){
							current = percentCompleted;
							notification.contentView.setProgressBar(R.id.status_progress, 100, current, false);
							notificationManager.notify(42, notification);
						}						
					}

					@Override
					public void onUploadFailed(LiveOperationException exception,LiveOperation operation) {
						notification.contentView.setImageViewResource(R.id.status_icon, R.drawable.ic_delete);		
			            notification.contentView.setTextViewText(R.id.status_text, DownloadService.this.getString(R.string.msg_upload_fail)+" "+name+".");
						notificationManager.notify(42, notification);
					}

					@Override
					public void onUploadCompleted(LiveOperation operation) {
						JSONObject result = operation.getResult();
						if (result.has(JsonKeys.ERROR)) {
							notification.contentView.setImageViewResource(R.id.status_icon, R.drawable.ic_delete);		
				            notification.contentView.setTextViewText(R.id.status_text, DownloadService.this.getString(R.string.msg_upload_fail)+" "+name+".");
							notificationManager.notify(42, notification);
							return;
						}
						

			            notification.contentView.setImageViewResource(R.id.status_icon, R.drawable.ic_yes);		
			            notification.contentView.setTextViewText(R.id.status_text, name);
						notificationManager.notify(42, notification);

					}
				});
	}
	
	private int computePrecentCompleted(long totalBytes, long bytesRemaining) {
        return (int) (((float)(totalBytes - bytesRemaining)) / totalBytes * 100);
    }
}
